package org.duang.kit;

import java.net.URISyntaxException;

import org.duang.server.DuangServer;

import com.aliyun4j.utils.Tools;

public class ServerKit {
	private String webAppDir;
	private int port;
	private String context;
	private int minPort = 8760;
	private int maxPort = 8769;
	private static ServerKit dserver;
	public static ServerKit duang() {
		if (dserver == null) {
			dserver = new ServerKit();
		}
		return dserver;
	}
	
	public ServerKit webAppDir(String webAppDir){
		if(ToolsKit.isEmpty(webAppDir)) throw new IllegalStateException("webAppDir is null");
		this.webAppDir="";
		this.webAppDir = webAppDir;
		return dserver;
	}
	
	public ServerKit port(int port){
		if(port < minPort || port > maxPort) throw new IllegalStateException("port only range is "+minPort+"~"+maxPort);
		this.port = port;
		return dserver;
	}
	
	public ServerKit context(String context){
		if(ToolsKit.isEmpty(context)) throw new IllegalStateException("context is null");
		this.context = context;
		return dserver;
	}
	
	private String getWebAppPath() {
		String path = "";
		try {
			path = PathKit.class.getResource("").getPath();
//			path = PathKit.class.getResource("/").toURI().getPath();
		} catch (Exception e) {
			path = PathKit.class.getResource("").getPath();
		}
		path = path.substring(path.lastIndexOf(":")+1, path.length());
		String rootPath = new java.io.File(path).getParentFile().getAbsolutePath().trim();
		if(rootPath.indexOf("WEB-INF") > -1){
			rootPath = rootPath.substring(0, rootPath.indexOf("WEB-INF")-1);			
		}
		PathKit.setWebRootPath(rootPath);
		return rootPath+ "/" + webAppDir.trim();
	}
	
	public void run() {
//		if(Tools.isEmpty(webAppDir)) webAppDir = "WebRoot";
		if( Tools.isEmpty(context) ) context = "/";
		if(port == 0) port = minPort;
		DuangServer ds = new DuangServer();
		ds.init(getWebAppPath(), port, context);
		ds.start();
	}
}
